package com.czxy.changgou3.controller;

import com.czxy.changgou3.config.JwtProperties;
import com.czxy.changgou3.pojo.User;
import com.czxy.changgou3.service.AuthService;
import com.czxy.utils.JwtUtils;
import com.czxy.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/21
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public BaseResult login(@RequestBody User user){
        //校验验证码--使用后删除
        String redisCode = stringRedisTemplate.opsForValue().get("login" + user.getUsername());
        //删除
        stringRedisTemplate.delete("login"+user.getUsername());

        if (redisCode == null){
            return BaseResult.error("验证码无效");
        }
        if (!redisCode.equalsIgnoreCase(user.getCode())){
            return BaseResult.error("验证码错误");
        }
        //登录
        User login = authService.login(user);

        if (login != null){
            System.out.println("登陆成功");
            // 生产token，并响应
            String token = JwtUtils.generateToken(login, jwtProperties.getExpire(), jwtProperties.getPrivateKey());

            return BaseResult.ok("登录成功")
                    .append("loginUser",login)
                    .append("token",token);
        }else {
            return BaseResult.error("用户名或密码错误");
        }
    }


}
